package com.ys.utils.redis.message;

import com.alibaba.fastjson.JSON;
import com.ys.utils.redis.Redis;
import com.ys.utils.spring.base.SpringTool;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

@Data
@Accessors(chain = true)
public class RedisMessage implements Serializable {
    private static final long serialVersionUID = -1L;
    private String queueOrTopic;
    private String message;
    private Map data;

    public static RedisMessage getInstence(String queueOrTopic) {
        return new RedisMessage(queueOrTopic);
    }
    public void sendQueue() {
        long i = Redis.list.lpush(this.getQueueOrTopic(), JSON.toJSONString(this));
        if(i==1) {
            System.err.println("发送mq成功："+this.getQueueOrTopic());
        }else {
            System.err.println("发送mq失败："+this.getQueueOrTopic());
        }
    }
    public void sendTopic() {
        this.getRedis().convertAndSend(this.getQueueOrTopic(), this);
    }

    private RedisTemplate<String, Object> getRedis() {
        return (RedisTemplate<String, Object>) SpringTool.getBean("redisTemplate");
    }

    public RedisMessage appendData(Object prop, Object data) {
        if (this.data == null) {
            this.data = new HashMap<>();
        }
        this.data.put(prop, data);
        return this;
    }
    public RedisMessage appendData(Map data) {
        if (this.data == null) {
            this.data = new HashMap<>();
        }
        this.data.putAll(data);
        return this;
    }
    private RedisMessage(){}
    private RedisMessage(String queueOrTopic){
        this.queueOrTopic = queueOrTopic;
    }
}
